package com.train.controller;


import com.train.pojo.User;
import com.train.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.util.Collection;

@Controller
public class UserController {

    @Autowired
    UserService userService;

    //查询所有考勤卡，返回列表页面
    @GetMapping("/user")
    public String list(@ModelAttribute("msg")String msg, @ModelAttribute("msg")String msgCode, Model model){
        Collection<User> users = userService.selectAllUser();
//        将结果放在请求中
        model.addAttribute("users",users);
        return "user/userList.html";
    }


    //to考勤卡添加页面
    @GetMapping("/addUser")
    public String toAdd(){
        return "user/addUser.html";
    }

    //员工添加功能，使用post接收
    @PostMapping("/addUser")
    public String add(User user, RedirectAttributes rettr){
        //保存员工信息
        userService.addUser(user);
        rettr.addFlashAttribute("" +
                "msg","用户添加成功");
        rettr.addFlashAttribute("msgCode","200");
        return "redirect:/user";
    }

    //to员工修改页面
    @GetMapping("/user/{id}")
    public String toUpdateCard(@PathVariable("id") Integer id, Model model){

        User user=userService.selectUserByid(id);
        model.addAttribute("user",user);

        return "user/updateUser.html";
    }

    @PostMapping("/updateUser")
    public String updateCard(User user,RedirectAttributes rettr){
        userService.updateUser(user);
        //回到员工列表页面
        rettr.addFlashAttribute("" +
                "msg","用户修改成功");
        rettr.addFlashAttribute("msgCode","200");
        return "redirect:/user";
    }

    @GetMapping("/delUser/{id}")
    public String deleteCard(@PathVariable("id")Integer id, RedirectAttributes rettr, HttpSession session){
        Integer userId=(Integer) session.getAttribute("userId");
        System.out.println(session.getAttribute("userId"));
        //根据id删除员工
        if (userId!=id){
            userService.deleteUser(id);
            rettr.addFlashAttribute("" +
                    "msg","用户删除成功！");
            rettr.addFlashAttribute("msgCode","200");
            return "redirect:/user";
        }
        else{
            rettr.addFlashAttribute("" +
                    "msg","不能删除自己！");
            rettr.addFlashAttribute("msgCode","400");
            return "redirect:/user";
        }
    }
}

